// pages/live/live.js
var app = getApp()
const $api = require('../../utils/api.js').API;
import AliRtcEngine from "../../utils/aliyun-rtc-wx-sdk.js";
const ins = AliRtcEngine.getInstance(this)

// const AliyunRTC = require('aliyun-rtc-wx-sdk');
// const rtcEngine = AliyunRTC.createEngine
// console.log(crypto,654)
import {
  InteractionEngine,
  InteractionEventNames,
  InteractionMessageTypes
} from '../../utils/aliyun-interaction-sdk.mini.js';
import services from '../../utils/services';
import {
  convertToCamel
} from '../../utils/common.js';
import {
  LatestLiveidStorageKey
} from '../../utils/constants';
import {
  CustomMessageTypes,
  MaxMessageCount
} from '../../utils/constantsNew';
// 每次进入重新创建互动消息实例，并更新 globalData 中的数据
// const ins = AliRtcEngine.getInstance(this)
app.globalData.interaction = ins;
const interaction = ins;
//console.log(getApp().globalData, 668)
// getApp().globalData
// //console.log(ins,987)

Page({

  /**
   * 页面的初始数据
   */
  data: {
    height: app.globalData.height,
    pure: true,
    roomInfo: {},
    bullets: [],
    inputHeight: '0',
    list: [],
    commentList: [],
    timers: [],
    drawTimeSet: null, //礼包倒计时

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.setStorageSync('jd-information', false)
  },
  // onReady() {
  //   const player = wx.createLivePlayerContext('testPlayer');
  //   player.play();
  //   player.onPlay(() => {
  //     console.log("播放开始"); // 测试事件监听
  //   });
  // },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let _this = this
    let jdinformation = wx.getStorageSync('jd-information')
    if (jdinformation) {
      wx.setStorageSync('jd-information', false)
      return
    }
    $api.getuserinfo({
      login_token: wx.getStorageSync('login_token'),
    }).then((res) => {

      if (res.data.code == 0) {
        _this.getAliveInfo()
        _this.setData({ wdl: false })
      } else {
        wx.login({
          success(res) {
            $api.getOpenid({
              js_code: res.code
            }).then((res) => {
              _this.setData({
                openidUser: res.data.data.openid
              })
              _this.getAliveInfo()
              _this.setData({ wdl: true })
              // wx.setStorageSync('u', res.data.data.openid)
            })
          }
        })
      }
    }).catch((err) => {
      _this.setData({
        loadModal: false
      })
    })

  },
  getAliveInfo() {
    let _this = this
    $api.getAliveInfo({
      login_token: wx.getStorageSync('login_token'),
    }).then((res) => {
      let data = res.data.data
      if (!data) {
        wx.showToast({
          title: '暂无直播',
          icon: 'none',
          duration: 2000
        })
        setTimeout(() => {
          wx.navigateBack({
            delta: 1,
            fail: (res) => {
              console.log(res)
              wx.reLaunch({
                url: '/pages/home/home',
              })
            },
          })
        }, 1000)

      } else {
        console.log(data, 1236)
        _this.setData({
          userId: data.user_id,
          aly_live_id: data.aly_live_id,
          liveInfo: data
        })
        _this.fetchRoomDetail(data.aly_live_id, data.user_id);
        _this.zhibo();
        if (!_this.data.wdl) {

        }

        if (_this.data.wdl) {
          return
        } else {
          // _this.getlivefudai()
          let sign_time_data = wx.getStorageSync('sign_time_data')
          let sign_time_cook = sign_time_data.aly_live_id == data.aly_live_id ? sign_time_data.sign_time_cook : 0
          console.log(data.sign_time)
          let qdtype = false //模拟没签到
          if (sign_time_data.livesign_type && sign_time_data.aly_live_id == data.aly_live_id) {
            // 已经签过道且同场不需要再计算时间
          } else {
            if (!qdtype && data.sign_time) {
              if (sign_time_cook >= data.sign_time) {
                _this.setData({
                  open_sign_qd: true,//签到弹窗出现
                  open_sign_type_look: true,
                  open_sign_qd_time_None: true
                })
              } else {
                sign_time_cook = sign_time_cook ? sign_time_cook : 0
                sign_time_cook++
                _this.setData({ sign_time_cook, open_sign_type_look: false })
                setTimeout(() => {
                  _this.qdOutTime()
                }, 1000)
              }
            }
          }

          // 直播商品
          console.log('zouzhemei')
          _this.getlivegoods()
        }

      }
      _this.setData({
        loadModal: false,
      })
    }).catch((err) => {
      _this.setData({
        loadModal: false
      })
    })
  },
  qdOutTime() {
    let _this = this
    let sign_time_cook = _this.data.sign_time_cook
    let liveInfo = _this.data.liveInfo
    // liveInfo.sign_time = 10
    // console.log(sign_time_cook,_this.data.open_sign_qd)
    if (sign_time_cook >= liveInfo.sign_time) {
      // console.log(1)
      let open_sign_qd = JSON.parse(JSON.stringify(true))
      let open_sign_qd_time = 5
      setTimeout(() => {
        _this.setData({
          open_sign_qd,//签到弹窗出现
          open_sign_qd_time,
          open_sign_type_look: true
        })

        _this.outTimeQt()
      }, 1000)

    } else {
      sign_time_cook++
      _this.setData({
        sign_time_cook,
        open_sign_type_look: false
      })
      let sign_time_data = {
        sign_time_cook: sign_time_cook,
        aly_live_id: _this.data.aly_live_id,
      }
      wx.setStorageSync('sign_time_data', sign_time_data);
      setTimeout(() => {
        _this.qdOutTime()
        _this.setData({
          open_sign_qd: false,
        })
      }, 1000)
    }
  },
  outTimeQt() {
    let _this = this
    let open_sign_qd_time = _this.data.open_sign_qd_time
    if (open_sign_qd_time > 0) {
      open_sign_qd_time--;
      setTimeout(() => {
        _this.outTimeQt()
        _this.setData({ open_sign_qd_time })

      }, 1000)
    } else {
      _this.setData({ open_sign_qd_time: 0, open_sign_qd: false, open_sign_qd_time_None: false, })
    }
  },
  onopenqd() {
    this.setData({ open_sign_qd_time_None: true, open_sign_qd: true })
  },
  golivesign() {
    let _this = this
    $api.livesign({
      aly_live_id: _this.data.aly_live_id,
      login_token: wx.getStorageSync('login_token'),
    }).then((res) => {
      if (res.data.code == 0) {
        wx.showToast({
          title: '签到成功',
          icon: 'none',
          duration: 2000
        })
        let sign_time_data = {
          sign_time_cook: _this.data.sign_time_cook,
          aly_live_id: _this.data.aly_live_id,
          livesign_type: true
        }
        wx.setStorageSync('sign_time_data', sign_time_data);
        _this.setData({
          open_sign_qd_time_None: false,
          open_sign_qd: false,
          loadModal: false,
          open_sign_type_look: false
        })
      } else if (res.data.code == 2) {
        let open_sign_qd = JSON.parse(JSON.stringify(false))
        console.log(open_sign_qd)
        let sign_time_data = {
          sign_time_cook: _this.data.sign_time_cook,
          aly_live_id: _this.data.aly_live_id,
          livesign_type: true
        }
        wx.setStorageSync('sign_time_data', sign_time_data);
        _this.setData({
          open_sign_qd_time_None: false,
          open_sign_qd: false,
          loadModal: false,
          open_sign_type_look: false
        })
        _this.setData({
          open_sign_qd_time_None: false,
          open_sign_qd_time: 0,
          open_sign_qd,
          loadModal: false,
          open_sign_type_look: false
        })
        wx.showToast({
          title: res.data.msg,
          icon: 'none',
          duration: 2000
        })

      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none',
          duration: 2000
        })
      }

    }).catch((err) => {
      _this.setData({
        loadModal: false
      })
    })
  },
  fetchRoomDetail(roomId, userid) {
    console.log(roomId, userid, 123)
    let _this = this
    userid = _this.data.openidUser ? _this.data.openidUser : userid
    if (this.data.fetching) {
      return;
    }
    // wx.showLoading({
    //   title: '直播间数据加载中...',
    // });
    this.setData({
      fetching: true
    })
    services
      .getRoomDetail(roomId, userid)
      .then((res) => {
        const data = convertToCamel(res);
        // this.$store.commit('liveroom/updateInfo', data);
        // 缓存当前直播间id
        wx.setStorage({
          key: LatestLiveidStorageKey,
          roomId: roomId,
          userid: userid,
        });
        this.setData({
          fetching: false
        })
      })
  },
  //直播数据
  zhibo() {
    var _this = this;
    // 获取设备号deviceId，唯一标识当前设备
    let deviceId = '';
    wx.getSystemInfo({
      success: res => {
        deviceId = res.model;
      }
    })
    const userId = _this.data.userId;
    if (!userId) {
      wx.login({
        success(res) {
          request.post({
            s: "User.center.getWxUserInfo",
            code: res.code
          }, res => {
            let openid = res.data.data.openid;
            _this.agetToken(openid)
          })
        }
      })
    } else {
      _this.agetToken(userId)
    }




    // wx.showLoading({
    //   title: '加载中...',
    //   mask: true
    // })

  },
  agetToken(e) {
    console.log(e)
    let userId = e
    var _this = this;
    // 获取设备号deviceId，唯一标识当前设备
    let deviceId = '';
    wx.getSystemInfo({
      success: res => {
        deviceId = res.model;
      }
    })
    _this.setData({
      livePlayer: _this.data.liveInfo
    })
    if (!_this.data.openidUser) {
      $api.getaccesstoken({
        login_token: wx.getStorageSync('login_token'),
        deviceId: deviceId,
        deviceType: 'web'

      }).then((res) => {
        let data = res.data.data
        console.log(data, 123)
        var result = res.data.data;
        // resolve(result);
        let user_info = {
          authToken: data.AccessToken,
          expire: new Date(),
          userId: userId,
          userName: wx.getStorageSync('nick_name') ? wx.getStorageSync('nick_name') : '臻元气用户',
        }
        wx.setStorageSync('user_info', user_info)
        _this.setData({
          accessToken: data.AccessToken,
          AccessTokenExpiredTime: data.AccessTokenExpiredTime,
          livePlayer: _this.data.liveInfo
        })
        _this.initInteraction()
        interaction.on("remoteUserOnLineNotify", (eventData) => {
          _this.handleReceivedMessage(eventData || {});

        });
        wx.setStorageSync('groupId', _this.data.liveInfo.aly_live_id)
        _this.setData({
          loadModal: false,
        })
      }).catch((err) => {
        _this.setData({
          loadModal: false
        })
      })

    } else {
      _this.setData({
        livePlayer: _this.data.liveInfo
      })
    }

  },
  async initInteraction(groupId) {
    let _this = this
    // let livePlayer = _this.data.livePlayer
    //console.log(wx.getStorageSync('nick_name'), 654211)
    let userNick = wx.getStorageSync('nick_name') ? wx.getStorageSync('nick_name') : '臻元气用户'
    console.log(userNick)
    try {
      // 获取token
      // const base64Token = await fetchToken();
      let appId = 'wx168469166f2b73fb'; // 从控制台获取
      let appKey = '198f41589d7dad4a2074ee979465b4ee'
      // let appSecret = '1395db9f99ac06c9f840cefd26eacc70'; // 从控制台获取，注意请勿在生产环境露出您的 AppKey
      let channelId = wx.getStorageSync('user_id'); // 可以修改为您的频道ID（仅支持英文字母、数字）
      let userId =  wx.getStorageSync('user_id'); // 可以修改为您的用户ID（仅支持英文字母、数字）
      let userName = wx.getStorageSync('nick_name') ? wx.getStorageSync('nick_name') : '臻元气用户'; // 可以修改为您的用户名（支持中文）
      let timestamp = Math.floor(Date.now() / 1000) + 3600; // 一个小时后过期
      let token =_this.data.accessToken; // token
      console.log(token.length,6665)
      // const { pusherAttributes, playerList } = await interaction.joinChannel(token, userName);
      let info = {
        channelId,
        userId,
        appId,
        token,
        timestamp,
      }
      const { pusherAttributes, playerList } = await interaction.joinChannel(info, userName);
      // let token =accessToken;
      // console.log(accessToken,36665)
      // interaction.generateToken(appSecret, userid, timestamp);
      // const { pusherAttributes, playerList } = await interaction.joinChannel({
      //   channelId,
      //   userId,
      //   appId,
      //   token,
      //   timestamp,
      // }, userName);
      // await interaction.joinGroup({
      //   groupId: livePlayer.aly_live_id,
      //   userNick: wx.getStorageSync('nick_name') ? wx.getStorageSync('nick_name') : '臻元气用户',
      //   //nick_name没有先用用 username
      //   userAvatar: '', // 随机取头像
      //   broadCastType: 2, // 广播所有人
      //   broadCastStatistics: true,
      // });
      // console.log(livePlayer.aly_live_id, 123321)
      // _this.setData({
      //   joinedGroupId: livePlayer.aly_live_id //groupId;
      // })
      // // .joinedGroupId =   '9b57a01b-387f-45c0-bd78-982abc22465c'//groupId;
      // // return
      // // 检查更新自己信息
      // _this.updateSelfInfo();
      // // 更新直播统计数据
      // _this.updateGroupStatistics();
      // wx.hideLoading();
      console.log('成功没', e);
    } catch (e) {
      console.log('加入消息组失败', e);
    }
  },
   
  updateSelfInfo() {
    let _this = this
    console.log(_this.data.joinedGroupId)
    const userData = services.getUserInfo();
    interaction.getGroupUserByIdList({
      groupId: _this.data.joinedGroupId,
      userIdList: [wx.getStorageSync('user_id')],
    }).then((res) => {
      const info = ((res || {}).userList || [])[0];
      if (info) {
        const muteBy = info.muteBy || [];
        let roomInfo = _this.data.roomInfo
        roomInfo.selfMuted = muteBy.includes('user')
        roomInfo.groupMuted = muteBy.includes('group')
      }
    });
  },
  updateGroupStatistics() {
    let _this = this
    interaction.getGroupStatistics({
      groupId: _this.data.joinedGroupId,
    })
      .then((res) => {
        console.log(res, 123654)
        let pv = wx.getStorageSync('pv')
        if (res.pv) {
          wx.setStorageSync('pv', res.pv);
        }

        let roomInfo = _this.data.roomInfo
        roomInfo.metrics = {
          pv: res.pv ? res.pv : pv,
          uv: res.uv,
          likeCount: res.likeCount ? res.likeCount : '',
          onlineCount: res.onlineCount,
        }
        _this.setData({
          roomInfo,
          likeCount: res.likeCount ? res.likeCount : ''
        })
        // this.$store.commit('liveroom/updateMetrics', {
        //   pv: res.pv,
        //   uv: res.uv,
        //   likeCount: res.likeCount,
        //   onlineCount: res.onlineCount,
        // });
      })
      .catch((res) => {
        //console.log(res, 1111)
      });
  },
  // 处理接收到的信息
  handleReceivedMessage(eventData) {
    console.log(eventData, 65658)
    let _this = this
    const {
      type,
      data,
      messageId,
      senderId,
      senderInfo = {}
    } = eventData || {};
    const nick_name = senderInfo.userNick || senderId;
    console.log('chatbox 消息', eventData, 666);
    let roomInfo = _this.data.roomInfo

    let date = new Date();
    let year = date.getFullYear(); //年
    let month = date.getMonth() + 1; //月
    let strDate = date.getDate(); //日  
    let hours = date.getHours(); //时
    let minutes = date.getMinutes(); //分
    let seconds = date.getSeconds(); //秒
    let time = year + ' ' + month + ' ' + strDate + ' ' + hours + ' ' + minutes + ' ' + seconds
    let comeName = _this.data.comeName
    let info = JSON.stringify(eventData)
    if (info == comeName) {
      return
    } else {
      _this.setData({
        comeName: info
      })
    }
    switch (type) {
      case InteractionMessageTypes.PaaSUserJoin:
        // 用户加入聊天组，更新直播间统计数据
        //console.log('用户加入聊天组，更新直播间统计数据', 123)

        _this.setData({
          likeCount: data.statistics ? data.statistics.likeCount : ''
        })


        _this.handleUserJoined(nick_name, data, messageId);

        break;
      case CustomMessageTypes.Comment:
        // 接收到评论消息
        console.log('接收到评论消息', 123)
        if (data && data.content) {
          //console.log(data && data.content, 333333333)
          _this.addMessageItem(data, nick_name, messageId, time, senderId);
        }
        break;
      case InteractionMessageTypes.PaaSMuteGroup:
        _this.data.text = '';
        //console.log('主播已开启全员禁言', 123)

        roomInfo.groupMuted = true
        _this.showToast('主播已开启全员禁言');
        break;
      case InteractionMessageTypes.PaaSCancelMuteGroup:
        //console.log('主播已解除全员禁言', 123)
        roomInfo.groupMuted = false
        _this.showToast('主播已解除全员禁言');
        break;
      case InteractionMessageTypes.PaaSMuteUser:
        //console.log(eventData, 1236541235)
        this.handleMuteUser(true, data);

        break;
      case InteractionMessageTypes.PaaSCancelMuteUser:
        //console.log(eventData, 12365484848)
        this.handleMuteUser(false, data);

        break;
      case CustomMessageTypes.NoticeUpdate:
        // banner 组件中的公告内容更新
        //console.log('公告已更新', 123)

        if (typeof data.notice === 'string') {
          roomInfo.notice = data.notice
          _this.showToast('公告已更新');
        }
        break;
      default:
        console.log(eventData, 123654666)
        console.log(data, 123654666)
        if (data && senderId == '111667') {
          _this.addMessageItem(data, nick_name, messageId, time, senderId);
        } else {
          _this.setData({
            likeCount: data.likeCount ? data.likeCount : ''
          })
        }

        break;
    }

    _this.setData({
      roomInfo
    })
  },
  onHide() {
    // interaction.logout();
    console.log(123, 66)
    let _this = this
    // interaction.close();
    // _this.onShow();
    // interaction.leaveGroup({
    //   groupId: _this.data.joinedGroupId,
    // })
    wx.setStorageSync('jd-information', true)
    clearInterval(_this.qdOutTime)
  },
  handleUserJoined(nick_name, data, messageId) {
    let _this = this
    console.log(data, 1233)
    // 更新统计数据
    if (data && data.statistics) {
      let pv = wx.getStorageSync('pv')
      if (data.statistics.pv) {
        wx.setStorageSync('pv', data.statistics.pv);
      }
      let roomInfo = _this.data.roomInfo
      roomInfo.metrics = data.statistics
      roomInfo.metrics.pv = roomInfo.metrics.pv ? roomInfo.metrics.pv : pv
    }
    // _this.addBulletItem(nick_name, messageId);
  },
  // 用于显示会消失的的气泡消息，如 入会 相关
  addBulletItem(nick_name, messageId) {
    let _this = this
    let item = {
      id: messageId,
      text: `${nick_name} 进入了直播间`,
    };
    let bullets = _this.data.bullets
    bullets.push(item);
    this.setData({
      bullets
    })
    setTimeout(() => {
      const i = bullets.indexOf(item);
      if (i !== -1) {
        bullets.splice(i, 1);
        _this.setData({
          bullets
        })
      }
    }, 1500);
    // myJinRoom


    var nick = wx.getStorageSync('nick_name') ? wx.getStorageSync('nick_name') : '臻元气用户';
    //nick_name没有先用用 username
    if (nick) {
      let userContent = _this.data.userContent
      // if (userContent == ('$^进入直播间^$' + nick + '$' + _this.data.hd.ranking)) {
      //   return
      // }
      // request.post({
      //   s: "User.aliyunLive.sendCoupon",
      //   username: wx.getStorageSync('username'),
      //   user_id: wx.getStorageSync('user_id'),
      //   time: wx.getStorageSync('time'),
      //   key: wx.getStorageSync('key'),
      //   content: '$^进入直播间^$' + nick + '$' + _this.data.hd.ranking
      // }, res => {
      //   let userContent = '$^进入直播间^$' + nick + '$' + _this.data.hd.ranking
      //   _this.setData({
      //     userContent
      //   })
      // })
    }

  },
  //键盘弹起
  inputFocus(e) {
    var _this = this;
    var inputHeight = 0
    if (e.detail.height) {
      inputHeight = e.detail.height
    }
    _this.setData({
      inputHeight: inputHeight + 'px'
    })
  },
  //键盘收起
  inputBlur() {
    this.setData({
      inputHeight: '0'
    })
  },
  // 发送消息
  handleConfirm(evt, type) {
    let _this = this
    let content = type ? evt : evt.detail.value
    if (
      !content ||
      !_this.data.joinedGroupId ||
      _this.data.sending ||
      _this.data.roomInfo.groupMuted ||
      _this.data.roomInfo.selfMuted
    ) {
      return;
    }
    const options = {
      groupId: _this.data.joinedGroupId,
      type: 10001,

      data: JSON.stringify({
        content: content,
        nick: wx.getStorageSync('nick_name') ? wx.getStorageSync('nick_name') : '臻元气用户',
        rank: 0
      }),
    };
    interaction
      .sendMessageToGroup(options)
      .then(() => {
        //console.log('发送成功');
        if (type) {
          //用户首次发抽奖弹幕

        }
        _this.setData({
          inputValue: ''
        })
      })
      .catch((err) => {
        //console.log('发送失败', err);
        // if(err.body.code == 'Forbidden.Message.HasBeenMute'){
        wx.showToast({
          title: '当前已被禁言，如有疑问，请联系客服',
          icon: 'none',
          duration: 2000
        })
        // }

      })
      .finally(() => {
        this.sending = false;
      });
  },
  // 添加评论
  addMessageItem(data, nickName, messageId, time, senderId) {
    // addBulletItem
    let _this = this
    console.log(data, 998965656)
    let content = data.content ? data.content : data

    //console.log(time, content, _this.data.Cftime, _this.data.Cfcontent)
    if (time == _this.data.Cftime && content == _this.data.Cfcontent) {
      return
    }
    _this.setData({
      Cfcontent: content,
      Cftime: time
    })
    if (content.indexOf('发布抽奖') != -1) {
      _this.getlivefudai()

    } else if (content.indexOf('抽奖结束') != -1) {

    } else if (content.indexOf('商品更新') != -1) {
      _this.getlivegoods()
    } else {
      const mid = `m_${messageId}`;
      let messageItem = {}
      // var array = content.split("^");
      // var array2 = array[2].split("$")
      messageItem = {
        rank: data.rank ? data.rank : content,
        messageId: _this.data.list.length,
        nickName: data.nick ? data.nick : nickName,
        content: content,
        user_id: senderId
      }
      // if (content.indexOf("$^") != -1) {
      //   var array = content.split("^");
      //   var array2 = array[2].split("$")
      //   messageItem = {
      //     rank: data.rank ? data.rank : array[1],
      //     messageId: _this.data.list.length,
      //     nickName: data.nick ? data.nick : nickName,
      //     content: array2[1],
      //     user_id: senderId
      //   }
      // } else {
      //   messageItem = {
      //     ranking: -1,
      //     messageId: _this.data.commentList.length,
      //     name: data.nick ? data.nick : nickName,
      //     content: content,
      //     user_id: senderId
      //   }
      // }
      var receivedm = _this.data.receivedm;
      let scrollIntoViewId = _this.data.scrollIntoViewId
      let commentList = _this.data.commentList
      scrollIntoViewId = mid;
      console.log(messageItem, 6658)
      commentList.push(messageItem);
      if (commentList.length > MaxMessageCount) {
        commentList.shift();
      }
      //console.log(commentList, 998)
      _this.setData({
        commentList,
        scrollIntoViewId
      })
      _this.toBottom()

      _this.toBottom()
    }

  },
  //置于底部
  toBottom() {
    var _this = this;
    let len = _this.data.commentList.length;
    //console.log(len, '底部')
    let commentList = _this.data.commentList
    commentList.forEach((item, index) => {
      item.index = index + 1
    })
    setTimeout(() => {
      if (len > 0 && commentList[len - 1]) {
        _this.setData({
          scrollIntoView: 'v' + len,
          commentList
        })
      }
    }, 500)

  },
  statechange(e) {
    console.log('live-player code:', e.detail.code, 333)
  },
  error(e) {
    console.error('live-player error:', e.detail.errMsg, 9999)
  },
  // 点赞
  handleClickLike() {
    // 执行发送点赞数据
    this.sendLike();
  },
  // 点赞
  sendLike() {
    let _this = this
    const count = _this.data.likeCount;
    //console.log(_this.data.likeCount, 555)
    const options = {
      groupId: _this.data.joinedGroupId,
      count: 1,
      broadCastType: 2,
    };
    let likeCount = 0;
    interaction.sendLike(options)
      .then((err) => {
        //console.log('sendLike 成功', err);
        likeCount = err.likeCount ? err.likeCount : ''
        _this.setData({
          likeCount
        })
      }).catch((err) => {
        // 若是失败了，加回 count
        //console.log('sendLike 失败', count, _this.data.likeCount);
        likeCount += count;
        _this.setData({
          likeCount
        })
      });
    // _this.setData({
    //   likeCount
    // })
  },
  showModal2(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
    clearInterval(this.data.couponTimeSet)
  },
  hideModal(e) {
    this.setData({
      modalName: null,
      barrinfo: { index: 'null' },
      open_sign_qd: false
    })
    clearInterval(this.data.couponTimeSet)
    clearInterval(this.data.qiandaoTime)
    clearInterval(this.data.couponxsTimeSet)

    this.data.timers.forEach((intervalId) => {
      clearInterval(intervalId);
    });

    // 清空timers数组
    this.setData({
      timers: []
    });

  },
  //确认推出
  onOut() {
    var _this = this;
    console.log(_this.data.joinedGroupId)
    interaction.leaveGroup({
      groupId: _this.data.joinedGroupId,
    }).then((res) => {
      wx.redirectTo({
        url: '/pages/home/home',
      })
    });

  },
  getlivegoods() {
    let _this = this
    console.log(111)
    $api.getlivegoods({
      aly_live_id: _this.data.aly_live_id
    }).then((res) => {
      let data = res.data.data
      console.log(data, 8855)
      // 测试
      // let data = {
      //   live_good_lists: [
      //     {
      //       good_id: 208,
      //       good_name: "富硒高钙蛋白粉（单盒）",
      //       good_no: "ZYQ066",
      //       live_price: "0.00",
      //       is_register: 2,
      //       image: "https://zyq.tjhaiqing.com/upload/bf/08c1eff8322e3130618a8d2129fc46.jpg"
      //     }
      //   ],
      //   small_good_info: {
      //     good_id: 218,
      //     good_name: "一次性鞋套（一组100双）",
      //     good_no: "ZYQ076",
      //     live_price: "100.00",
      //     is_register: 2,
      //     image: "https://zyq.tjhaiqing.com/upload/fc/3fb3b38a5c17026a565becad5296f1.jpg"
      //   }
      // }

      _this.setData({
        live_good_lists: data.live_good_lists,
        small_good_info: data.small_good_info,
        goodslist: res.data.data,
        NewgoodsType: !data.small_good_info ? false : true,
        triggered: false
      })
    }).catch((err) => {
      _this.setData({
        loadModal: false
      })
    })
  },
  showModal2(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
    // clearInterval(this.data.couponTimeSet)
  },
  //进入购物车
  onOrder() {
    let _this = this
    interaction.leaveGroup({
      groupId: _this.data.joinedGroupId,
    }).then((res) => {
      wx.navigateTo({
        url: '/pages/order/order',
      })
    })

  },
  //进入商品详情
  ondetails(e) {
    var _this = this;
    clearInterval(_this.data.drawTimeSet)

    if (e.currentTarget.dataset.goods_num <= 0 || e.currentTarget.dataset.sell_status == 1) {
      wx.showToast({
        title: '该商品已售罄',
        icon: 'none',
        duration: 2000
      })
    } else {

      // interaction.leaveGroup({
      //   groupId: _this.data.joinedGroupId,
      // }).then((res)=>{
      // wx.setStorageSync('jd-information', true)
      wx.removeStorageSync('address')
      wx.removeStorageSync('applyShop')
      wx.removeStorageSync('wait_pay')
      wx.removeStorageSync('giftId')
      wx.removeStorageSync('pay')
      wx.removeStorageSync('goodsList')
      wx.removeStorageSync('addressid')
      let info = e.currentTarget.dataset.info
      info.price = info.live_price
      info.id = info.good_id
      info.num = 1
      console.log(info)
      // let goodinfo = _this.data.goodinfo
      // goodinfo.num = 1
      let list = []
      list.push(info)
      list = JSON.stringify(list)
      let is_register = e.currentTarget.dataset.is_register
      // let _this = this
      wx.navigateTo({
        url: '/pages/reading/reading?state=3&&twoType=1&&zbgoodsType=1&&goods=' + list,
      })
      // if (is_register == 2) {
      //   wx.navigateTo({
      //     url: '/pages/Readingdetails/Readingdetails?pt=1&zbgoodsType=1&id=' + e.currentTarget.dataset.id,
      //   })
      // } else if (is_register == 0) {
      //   wx.navigateTo({
      //     url: '/pages/Readingdetails/Readingdetails?ep=1&zbgoodsType=1&id=' + e.currentTarget.dataset.id,
      //   })
      // }

    }

  },
  // 福袋
  fudaitup() {
    let _this = this
    _this.setData({
      fudaixxtype: true
    })
  },
  getlivefudai() {
    let _this = this
    var drawTimeSet = _this.data.drawTimeSet
    //console.log(drawTimeSet, 654222666666666666)
    clearInterval(drawTimeSet)
    $api.getlivefudai({
      aly_live_id: _this.data.aly_live_id,
      login_token: wx.getStorageSync('login_token'),
    }).then((res) => {
      let data = {
        id: 2,
        live_id: 62,
        award_num: 10,
        bullet_chat: "你说了算",
        start_time: "2025-08-19 00:00:00",
        end_time: "2025-08-19 15:50:00",
        good_id: 208,
        good_num: 2,
        status: 0,
        add_time: "2025-08-14 11:04:56",
        update_time: "2025-08-14 11:04:56",
        is_cj: 0,
        good_info: {
          good_id: 208,
          good_name: "富硒高钙蛋白粉（单盒）",
          good_no: "ZYQ066",
          live_price: "0.00",
          is_register: 2,
          image: "https://zyq.tjhaiqing.com/upload/bf/08c1eff8322e3130618a8d2129fc46.jpg"
        }
      }//测试数据
      let timeDq = new Date().getTime(); //当前时间
      let timestart = new Date(data.start_time).getTime(); //开始抽奖时间
      let timeend = new Date(data.end_time).getTime(); // 抽奖结束时间
      let fudaicjtype = 1 //1倒计时正在抽奖 //2未到抽奖时间 // 3抽奖结束
      console.log(timeDq, timestart, timeend)
      if (timestart > timeDq) {
        fudaicjtype = 2
      } else if (timeend < timeDq) {
        fudaicjtype = 3
      } else {
        let timesy = timeend - timeDq
        let countdown = msToMinuteCountdown(timesy);
        _this.setData({ timesy, countdown })

        drawTimeSet = setInterval(function () {
          let timeDq = new Date().getTime(); //当前时间
          let timestart = new Date(data.start_time).getTime(); //开始抽奖时间
          let timeend = new Date(data.end_time).getTime(); // 抽奖结束时间
          let timesy = timeend - timeDq
          if (timestart > timeDq) {
            fudaicjtype = 2
            _this.setData({ fudaicjtype })
            clearInterval(drawTimeSet)
          } else if (timeend < timeDq) {
            fudaicjtype = 3
            _this.setData({ fudaicjtype })
            clearInterval(drawTimeSet)
          } else {
            // var drawTimeSetNum = _this.data.timesy;
            // drawTimeSetNum--;
            // console.log(drawTimeSetNum)
            countdown = msToMinuteCountdown(timesy);
            _this.setData({
              timesy: timesy,
              drawTimeSet: drawTimeSet,
              countdown
            })
          }
        }, 1000)
      }
      _this.setData({
        fudaidata: data,
        fudailogotype: true,
        fudaicjtype
      })
    }).catch((err) => {
      _this.setData({
        loadModal: false
      })
    })
  },
  // 下拉刷新
  refresh: function (e) {
    var _this = this;
    //商品刷新
    _this.getlivegoods()
  },
})
function msToMinuteCountdown(ms) {
  // 转换为秒
  const totalSeconds = Math.floor(ms / 1000);

  // 计算分钟和剩余秒数
  let minutes = Math.floor(totalSeconds / 60);
  let seconds = totalSeconds % 60;
  minutes = minutes.toString().padStart(1, '0');
  seconds = seconds.toString().padStart(1, '0');

  // 或者保持数字类型但格式化显示：
  const formattedMinutes = minutes < 10 ? `0${minutes}` : minutes;
  const formattedSeconds = seconds < 10 ? `0${seconds}` : seconds;
  // 格式化为"X分钟X秒"
  return `${formattedMinutes}:${formattedSeconds}`;
}
// function generateRTCToken(appId, appKey, channelId, userId, timestamp) {
//   // 参数校验
//   if (!appId || !appKey || !channelId || !userId || !timestamp) {
//     throw new Error('Missing required parameters');
//   }
  
//   // 拼接签名字符串
//   const signContent = appId + appKey + channelId + userId + '' + timestamp;
  
//   // 计算SHA256哈希
//   // const hash = crypto.cryptosha256('sha256');
//   cryptosha256.update(signContent);
  
//   return hash.digest('hex');
// }